package com.lt.tccdemo.consumer;

import com.lt.tccdemo.db109.dao.TOrderMapper;
import com.lt.tccdemo.db109.model.TOrder;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author lucine
 * @version 1.0 2021/10/6 21:47
 */
@Component("MessageListener")
public class ChangeOrderStatus implements MessageListenerConcurrently {

    @Autowired
    private TOrderMapper orderMapper;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        if(msgs==null ||msgs.size()==0){
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        for (MessageExt msg:msgs) {
            String keys = msg.getKeys();
            String msgBody = new String(msg.getBody());
            System.out.println("msgBody = "+ msgBody);

            TOrder tOrder = orderMapper.selectByPrimaryKey(Integer.parseInt(keys));
            //todo 正常在系统中需要人工处理
            if(tOrder==null){
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
            try{
                //已支付
                tOrder.setOrderStatus(1);
                tOrder.setUpdateTime(new Date());
                //系统更新
                tOrder.setUpdateUser(0);
                orderMapper.updateByPrimaryKey(tOrder);
            }catch (Exception e){
                e.printStackTrace();
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        }

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
